package org.crud4j.validator;

import java.util.ArrayList;
import java.util.Collection;

/**
 * A Bean Validator
 * 
 * @author edgar.poce
 * @param <T>
 */
class CompositeBeanValidator<T> {

	private Collection<BeanValidator<T>> validators = new ArrayList<BeanValidator<T>>();

	public void validate(T bean) throws BeanValidatorException {

		Collection<ValidationResult> results = null;

		for (BeanValidator<T> validator : this.validators) {
			try {
				validator.validate(bean);
			} catch (BeanValidatorException e) {
				if (results == null) {
					results = new ArrayList<ValidationResult>();
				}
				results.addAll(e.getValidationResults());
			}
		}

		if (results != null) {
			throw new BeanValidatorException(bean, results);
		}

	}

	public void addBeanValidator(BeanValidator<T> validator) {
		this.validators.add(validator);
	}

}
